﻿using Signit.Sdk.Extentions;
using System.IO;
using System.Text;
using Viyi.Util;

namespace Signit.Sdk.Util
{
    class SignitStreamWriter
    {
        public readonly Stream Stream;
        private byte[] delimiter = new byte[0];
        private Encoding encoding = Encoding.UTF8;

        public SignitStreamWriter(Stream stream)
        {
            Stream = stream;
        }

        public SignitStreamWriter SetDelimiter(byte[] delimiter)
        {
            this.delimiter = delimiter ?? new byte[0];
            return this;
        }

        public SignitStreamWriter SetEncoding(string encoding)
        {
            this.encoding = Encoding.GetEncoding(encoding);
            return this;
        }

        public SignitStreamWriter SetEncoding(Encoding encoding)
        {
            this.encoding = encoding;
            return this;
        }

        public SignitStreamWriter Write(byte[] data)
        {
            Stream.Write(data);
            Stream.Write(delimiter);
            return this;
        }

        public SignitStreamWriter Write(string s)
        {
            process();
            return this;

            void process()
            {
                if (s == null) { return; }
                Stream.Write(s.ToByteArray(encoding))
                    .Write(delimiter);
            }
        }
    }
}
